#!/usr/bin/perl -w

use warnings "all";
use Getopt::Long;

#Declaration and initialization of variables
my $trace = "";
my $script_name = $0;
my @input_file;
my $file_size;
my $i;
my $file_tag;
my %file_tag_hash;
my $current_tag;

$opt_result = GetOptions (
  "input=s"   => \$trace,
  "help"       => \$help,
);

if(!$opt_result)
{
  print STDERR "$script_name: Invalid command line options!\n";
  print STDERR "$script_name: Use -help if you need it :)\n";
  die;
}

if($help)
{
  print_help();
  exit 0;
}

if(0 == open(INFILE, "$trace"))
{
  print STDERR "$script_name: Cannot open $trace for reading!\n";
  die;
}

system "rm -rf kernel_*";

@input_file = <INFILE>;
close(INFILE);

$file_size = scalar(@input_file);

$current_tag = "";
for($i=0; $i<$file_size; $i=$i+1)
{
  $line = $input_file[$i];

  if($line =~ m/^###(.*)/)
  {
    $file_tag = $1;
    if (!exists $file_tag_hash{$file_tag})
    {
      $kernel_tag = $file_tag;
      $kernel_tag =~ s/_.*//g;
      if (!(-d "kernel_$kernel_tag"))
      {
        system("mkdir kernel_$kernel_tag");
        system("mv config_$kernel_tag.txt kernel_$kernel_tag/config_$kernel_tag.txt");
        system("mv data_$kernel_tag.mem kernel_$kernel_tag/data_$kernel_tag.mem");
        system("mv instr_$kernel_tag.mem kernel_$kernel_tag/instr_$kernel_tag.mem");
      }
      @{$file_tag_hash{$file_tag}} = ();
    }

    $current_tag = $file_tag;
  }
  else
  {
    if ($current_tag ne "")
    {
        push(@{$file_tag_hash{$current_tag}}, $line);
    }
  }
}

foreach $file_tag_key (keys %file_tag_hash)
{
  #Open the output file and print the output
  $kernel_tag = $file_tag_key;
  $kernel_tag =~ s/_.*//g;
  if (0 == open(OUTFILE, ">kernel_$kernel_tag/${trace}_$file_tag_key"))
  {
    print STDERR "$script_name: Cannot open ${trace}_$file_tag_key for writing!\n";
    die;
  }
  print OUTFILE @{$file_tag_hash{$file_tag_key}};
  close(OUTFILE);
}

sub print_help
{
print STDOUT qq{$script_name:

DESCRIPTION:
        This script can be used to parse trace generated by multi2sim and generate traces ready to be 
        consumed by tracemon.

USAGE:
   $script_name -i <input_trace_name> [-h]

ARGUMENTS:

-i <input_trace_name> 
-input <input_trace_name>       This is a compulsory option; used to specify the name of trace to be parsed.

-h
-help                           Well, you know what this option is for! You couldn't be reading this otherwise.
};

}
